package com.lincoln.config;

import com.lincoln.bean.ApiCode;
import com.lincoln.bean.ApiCodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

/**
 * 异常拦截器
 *
 * @author lincoln
 * @since 2017/9/9
 */
@ControllerAdvice
public class ExpectionHandle {
    private static Logger logger = LoggerFactory.getLogger(ExpectionHandle.class);

    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    }

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     *
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "Lincoln");
    }

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ApiCodeException.class)
    public ApiCode errorApiHandler(ApiCodeException ex) {
        ApiCode apiCode = ex.getApiCode();
        if (apiCode == null) {
            return ApiCode.findCode(ApiCode.FAIL);
        }
        return apiCode;
    }

    @ResponseBody
    @ExceptionHandler(value = AccessDeniedException.class)
    public ApiCode accessDeniedException(AccessDeniedException ex) {
        return ApiCode.findCode(ApiCode.NOPERMISSION);
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ApiCode errorHandler(Exception ex) {
        logger.error("{}", ex);
        return ApiCode.findCode(ApiCode.FAIL);
    }


}